const app = getApp()
var util = require('../../../utils/utils')
import * as echarts from '../../../ec-canvas/echarts';
var initChart = null

function InitChart(chart, ylist, xlabel) {
  var options = {
    title: {
      left: 'center'
    },
    color: ["#eaff00"],
    grid: {
      top: 20,
      right: 20,
      bottom: 30
    },
    tooltip: {
      show: true,
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xlabel
    },
    yAxis: {
      x: 'center',
      type: 'value',
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      type: 'line',
      smooth: true,
      data: ylist
    }]
  }
  chart.setOption(options);
}

Page({
  data: {
    engineer:true,
    device_detail: {},
    device_id:'',
    allParams: [{
        text: '径向力',
        value: 'force'
      },
      {
        text: '第一相电流',
        value: 'phase_current_1'
      },
      {
        text: '第二相电流',
        value: 'phase_current_2'
      },
      {
        text: '旋转速率',
        value: 'speed'
      },
      {
        text: '负荷扭矩',
        value: 'torque'
      },
      {
        text: '振动信号',
        value: 'vibration_1'
      }
    ],
    time: '',
    timer: '',    //计时器
    i: 0,
    allConditionName: ["径向力","第一相电流","第二相电流","旋转速率","负荷扭矩","振动信号"],   //选择工况类型的标签名
    index: 0,
    result: [],        //接收获取的工况数据结果
    chartTimer: '',
    ec: {
      lazyLoad: true
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var device_id = app.globalData.device_detail.device_id
    this.setData({
      time: util.formatTime(new Date()),
      device_id: device_id,
      engineer:app.globalData.engineer
    })
    this.getAllParamsDatas(device_id)
    this.oneComponent = this.selectComponent('#mychart-dom-line');
  },
  //获取单个工况原始数据
  getSingParamData: function (DeviceId, attr, callback) {
    wx.request({
      url: 'https://phmlearn.com/component/data/paderborn',
      method: 'POST',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        device_id: DeviceId,
        attribute: attr,
        access_token: app.globalData.access_token
      },
      success: function (res) {
        callback(res)
      }
    })
  },
  //获取所有工况数据
  getAllParamsDatas: function (fanId) {
    wx.showLoading({
      title: '数据加载中',
    })
    const allParamsName = this.data.allParams;
    let promises = []
    for (let i = 0; i < allParamsName.length; i++) {
      let paramsKey = allParamsName[i].value
      if (i === 0) {
        this.getSingParamData(fanId, paramsKey, res => {
          console.log(res.data.data[paramsKey])
          this.getChartdata(res.data.data[paramsKey])
        })
      }
      promises.push(this.getSingParamData(fanId, paramsKey, res => {
        const data = res.data.data[paramsKey]
        this.setData({
          [`result[${i}]`]: {
            key: allParamsName[i].text,
            max: util.getMaxValue(data),
            min: util.getMinValue(data),
            arr: util.getDataArray(data)
          }
        })
      }))
    }
    Promise.all(promises).then(res => {
      this.startTimer()
      this.setDate()
      // wx.hideLoading()
    })
  },
  //获取折线图数据
  getChartdata: function (array) {
    wx.showLoading({
      title: '图表加载中',
    })
    if (this.data.chartTimer) {
      this.closeTimer(this.data.chartTimer)
    }
    let index = 0
    this.setData({
      chartTimer: setInterval(() => {
        if (index <= 8000) {
          this.setData({
            ylist: array.slice(index, index + 2560)
          })
          index+=1000
        } else {
          this.closeTimer(this.data.chartTimer)
          this.setData({
            ylist: array.slice(array.length - 2560, array.length - 1)
          })
        }
        this.oneComponent.init((canvas, width, height) => {
          const chart = echarts.init(canvas, null, {
            width: width,
            height: height
          });
          var xlabel = []
          var timestamp = (new Date()).valueOf();
          for(var i=0;i<2560;i++){
            var t1=new Date(timestamp)
            var tt1 = new String(t1)
            var ttt1 = tt1.split(' ')[4]
            xlabel.push(ttt1)
            timestamp -= 1000
          }
          InitChart(chart, this.data.ylist, xlabel) //赋值给echart图表
          wx.hideLoading()
          this.chart = chart;
          return chart;
        });
      }, 2000)
    })
  },
  //开启刷新时间定时器
  setDate: function () {
    this.setData({
      timer: setInterval(() => {
        this.setData({
          time: util.formatTime(new Date())
        })
      }, 1000)
    })
  },
  //开启刷新数据定时器
  startTimer: function () {
    this.setData({
      i: 0
    })
    this.setData({
      timer: setInterval(() => {
        if (this.data.i <= 3000) {
          this.setData({
            i: this.data.i + 1
          })
        } else {
          this.setData({
            i: 0
          })
          this.closeTimer(this.data.timer)
        }
      }, 1000)
    })
  },
  //关闭定时器
  closeTimer: function (time) {
    clearInterval(time)
  },
  editlog: function () {
    wx.navigateTo({
      url: '../makelog/makelog',
    })
  },
  //切换工况picker
  bindPickerChange: function (e) {
    this.setData({
      index: e.detail.value
    })
    let index = e.detail.value
    let arr = this.data.result[index].arr
    this.getChartdata(arr)
  },
  //页面卸载时清空定时器
  onUnload: function () {
    if (this.data.timer) {
      this.closeTimer(this.data.timer)
    }
    if (this.data.chartTimer) {
      this.closeTimer(this.data.chartTimer)
    }
  }
})